<template>
  <div>

    <h2>编辑用户 <router-link to="/users/index">返回</router-link> </h2>

    <form>
      <fieldset>
        <legend>编辑用户</legend>
        <p>
          姓名 <input type="text" v-model="form.name">
        </p>
        <p>
          年龄 <input type="number" v-model="form.age">
        </p>
        <p>
          性别
          <input type="radio" :value="1" v-model="form.gender">男
          <input type="radio" :value="2" v-model="form.gender">女
        </p>
        <p>
          <button @click="save">保存</button>
        </p>
      </fieldset>
    </form>
  </div>
</template>
<script>
import axios from 'axios';

const request = axios.create({
  baseURL: 'http://127.0.0.1:8081'
});
export default {
  data() {
    return {
      form: {
        name: '',
        age: '',
        gender: 1
      }
    };
  },
  computed: {
    id() {
      return this.$route.query.id;
    }
  },
  mounted() {
    this.getUserByID();
  },
  methods: {
    async getUserByID() {
      const { data } = await request.get(`/users/${this.id}`);
      this.form.name = data.name;
      this.form.age = data.age;
      this.form.gender = data.gender;
    },
    async save() {
      await request.patch(`/users/${this.id}`, {
        name: this.form.name,
        age: this.form.age,
        gender: this.form.gender,
      });
      this.$router.push('/users/index');
    }
  }
}

</script> 